<?php
/**
 * 整屋筛选
 */

namespace Beerus\Modules\Article\Controllers;

use Hhz\AdministrativeRegion\Region;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\brand\Brand;
use Doraemon\cache\Designer\MasterSlave;
use Doraemon\cache\JudgeArticle;
use Doraemon\model\AdminAccount\AdminAccountOperate;
use Doraemon\model\AdmUserType;
use Doraemon\model\Article as dbArticle;
use Doraemon\model\ContentSignExtend;
use Doraemon\model\DesignerOperatorBind\DesignerOperatorBind;
use Doraemon\model\DesignerTeam;
use Doraemon\model\KaDesigner;
use Doraemon\model\Member;
use Doraemon\model\Operator;
use Doraemon\service\AdmArticle\ArticleSearch;
use Doraemon\service\AdmArticle\FilterConfig;
use Doraemon\service\AdmArticle\Schedule;
use Doraemon\service\Article as sArticle;
use Doraemon\service\User as sUser;
use Doraemon\tools\BlockType;
use Doraemon\tools\IdParse;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\service\Designer\AuthService;
use Doraemon\model\DesignerAuth;

class ArticleSearchController extends Controller
{
    public function __construct(Request $request)
    {
        parent::__construct();
    }

    public function index(Request $request, Content $content)
    {
        Admin::script(
            <<<EOF
        $('input[type=radio][name=select_area]').on('ifChecked',function(){
            if(this.value == 1) {
                $("select.multiplearea").parent().parent().hide();
                $("select.province").parent().parent().show();
                $("select.city").parent().parent().show();
            }else {
                $("select.multiplearea").parent().parent().show();
                $("select.city").parent().parent().hide();
                $("select.province").parent().parent().hide();
            }
        });

        $('input[type=radio][name=is_audit_again]').on('ifChecked',function(){
            if(this.value == 0) {
                $("select.audit_time").parent().parent().hide();
            }else {
                $("select.audit_time").parent().parent().show();

            }
        });
        $('input[type=radio][name=select_area]:checked').trigger('ifChecked');

        console.log($('.Find-filter-group-label').val());

EOF
        );

        Admin::style('.column-title {width:15%;}');

        $url = $_SERVER["REQUEST_URI"];
        $data_url = explode('?', $url);
        $export_url = $data_url[1] ?: '';

        $requestParams = $request->all();

        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);

        if (empty($requestParams['user_type'])) {
            $requestParams['user_type'] = [
                Member::AUTH_DECO_COMPANY,
                Member::AUTH_USER_DESIGNER,
                Member::AUTH_USER_UNAUTH_DESIGNER
            ];
        }

        $requestParams['page_size'] = $pageSize;
        $requestParams['page'] = $page;

        $object = new ArticleSearch($requestParams);
        $solr_list = Schedule::getList($object);
        $article_ids = $solr_list['rows'] ?: [];
        if ($requestParams['nick'] && $object->uid == 0) {
            $article_ids = [];
        }
        $list = [];
        if ($article_ids && is_array($article_ids)) {
            $list = dbArticle::select("*", [
                "AND" => [
                    "aid" => $article_ids,
                    "status" => [
                        dbArticle::STATUS_WAIT_CHECK,
                        dbArticle::STATUS_SUCCESS,
                    ]
                ],
                'ORDER' => ['publish_time' => 'DESC']
            ]);

            //按照aiticle_id 排序
            $info = sArticle::getArticleBasicInfos($article_ids);
        }

        // 获取整屋案例重复情况
        $hashSameArticleInfos = JudgeArticle::multiGetSameInfos($article_ids);
        //运营评论列表
        $admin_comments = [];
        $comments = AdminAccountOperate::getByObjIds($article_ids, AdminAccountOperate::ACCOUNT_TYPE_COMMENT, BlockType::TYPE_ARTICLE);
        if ($comments && is_array($comments)) {
            foreach ($comments as $comment) {
                $admin_comments[$comment['obj_id']] = (string)Admin::user()->find($comment['admin_id'])->name;
            }
        }
        //运营点赞列表
        $admin_likes = [];
        $likes = AdminAccountOperate::getByObjIds($article_ids, AdminAccountOperate::ACCOUNT_TYPE_LIKE, BlockType::TYPE_ARTICLE);
        if ($likes && is_array($likes)) {
            foreach ($likes as $like) {
                $admin_likes[$like['obj_id']] = (string)Admin::user()->find($like['admin_id'])->name;
            }
        }

        $extendMap = [];
        $extendInfo = ContentSignExtend::getExtendInfoByNoteIds($article_ids);
        if ($extendInfo && is_array($extendInfo)) {
            foreach ($extendInfo as $value) {
                $extendMap[$value['obj_id']] = $value;
            }
        }

        $total = $solr_list['total'];
        if ($list && is_array($list)) {
            foreach ($list as &$val) {
                $val['cover_img_url'] = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $val['cover_pic_id'], ImgUrl::IMAGE_SIZE_O_500);
                $val['admin_tag'] = array_filter(explode(",", $val['admin_tag'])) ?: [];
                if ($info[$val['aid']] && is_array($info[$val['aid']])) {
                    $val['area_name'] = $info[$val['aid']]['article_info']['area_name'];
                    $val['like'] = $info[$val['aid']]['counter']['like'];
                    $val['favorite'] = $info[$val['aid']]['counter']['favorite'];
                    $val['comments'] = $info[$val['aid']]['counter']['comments'];
                    $val['read'] = $info[$val['aid']]['counter']['read'];
                    $val['nick'] = $info[$val['aid']]['user_info']['nick'];
                    $val['house_size'] = $info[$val['aid']]['article_info']['house_size'];
                    $val['house_stuff'] = $info[$val['aid']]['article_info']['house_stuff'] / 10000;
                    $val['house_construction'] = $info[$val['aid']]['article_info']['house_construction'];
                    if ($val['title'] != $info[$val['aid']]['article_info']['title']) {
                        $val['op_title'] = $info[$val['aid']]['article_info']['title'];
                    }
                    $val['user_type'] = $this->FormateType($info[$val['aid']]['user_info']['uid'], $info[$val['aid']]['user_info']['type']);
                    $adm_info = $this->FormateUserTag($info[$val['aid']]['user_info']['uid']);
                    $val['user_tag'] = $adm_info['user_tag'];
                    $val['quality'] = $adm_info['user_quality'];
                }


                if ($val['admin_score'] > 0 && $val['status'] == 1) {
                    $val['audit_status'] = 1;
                }
                if ($val['status'] == dbArticle::STATUS_WAIT_CHECK && $val['admin_score'] > 0) {
                    $val['audit_status'] = dbArticle::STATUS_WAIT_CHECK;
                }
                if ($val['status'] = dbArticle::STATUS_WAIT_CHECK && $val['admin_score'] == 0) {
                    $val['audit_status'] = 2;
                }

                $val['audit_status'] = FilterConfig::ARTICLE_STATUS[$val['audit_status']];
                $extend_info = json_decode($val['extend'], true) ?: [];
                if ($extend_info && is_array($extend_info)) {
                    $room_ids = $extend_info['live_room_ids'] ?: [];
                    if ($room_ids && is_array($room_ids)) {
                        $val['room_ids'] = implode(',', $room_ids);
                    }
                }

                // 案例重复信息
                $val['same_infos'] = array();
                if (isset($hashSameArticleInfos[$val['aid']]) && $hashSameArticleInfos[$val['aid']]) {
                    $sameInfos = json_decode($hashSameArticleInfos[$val['aid']], true);
                    $val['same_infos'] = $sameInfos;
                }
                //运营相关操作
                $val['admin_comment'] = (string)$admin_comments[$val['aid']];
                $val['admin_like'] = (string)$admin_likes[$val['aid']];
                $val['is_business'] = $extendMap[$val['aid']]['is_business'] ?: 0;
            }
            unset($val);
        }
        //获取域名前缀
        $preUrl = str_replace('beerus.', 'frieza.', str_replace('admin/article/search/index', '', $request->url()));
        //取出所有关系
        $uidList = array_column($list, 'uid');
        $uidList = array_unique($uidList); //去重
        //获取团队的uid
        $teamList =  DesignerTeam::getOrgUidByMemberUidList($uidList);
        //团队和子账号对应的map
        $teamMap = [];
        if (!empty($teamList)) {
            foreach ($teamList as $tv) {
                $teamMap[$tv['member_uid']] = $tv['org_uid'];
                $uidList[] = $tv['org_uid'];
            }
        }
        $uidList = array_unique($uidList); //去重
        //查找uid生效的订单
        $kaUidList =  KaDesigner::getWillEffectNByUidArr($uidList);
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);

        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $export_url, $kaUidList, $preUrl, $teamMap) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                //筛选
                $grid->filter(function (\Encore\Admin\Grid\Filter $filter) {
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('uid', 'Uid');
                        $filter->dropDown('Find', [
                            'article_id' => '文章id',
                            'nick' => '用户昵称',
                            'title' => "文章标题",
                            'op_title' => '运营精选标题',
                            'adm_remark' => '文章备注',
                            'admin_tag' => '文章标签'
                        ]);
                        $filter->equal('user_type', '用户身份')->checkbox([
                            Member::AUTH_DECO_COMPANY => '装修公司',
                            Member::AUTH_USER_DESIGNER => '设计师用户',
                            Member::AUTH_USER_UNAUTH_DESIGNER => '未认证设计师'
                        ]);
                        $filter->equal('confirmed', '用户标识')->checkbox(FilterConfig::USER_TYPE);
                        $filter->equal('quality', '用户质量')->checkbox(FilterConfig::QUALITY);
                        $filter->equal('high_check', '高级筛选')->checkbox(FilterConfig::HIGH_CHECK);
                        $filter->equal('score', '分数')->checkbox(FilterConfig::SCORE);
                        $filter->equal('tag_status', '标签状态')->radio(FilterConfig::TAG_STATUS);
                    });

                    $filter->column(1 / 2, function ($filter) {
                        $filter->between('release_time', '发布时间')->datetime();
                        $filter->between('user_update_time', '用户编辑时间')->datetime();
                        $filter->between('size', '面积大小');
                        $filter->between('stuff', '预算');
                        $filter->equal('room', '居室')->checkbox(FilterConfig::ROOM);

                        $top = Region::getProvincesList();
                        $filter->in('multiplearea', '地区(多选)')->multipleSelect($top);
                        $filter->equal('audit_status', '审核状态')->radio(FilterConfig::AUDIT_AGAIN)->default(0);
                        $filter->equal('is_have_repeat', '只看疑似重复案例')->checkbox(FilterConfig::IS_HAVE_REPEAT);
                    });
                    //条件展开
                    $filter->expand();
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->expandFilter();

                $grid->column("aid", 'id')->display(function () use ($preUrl) {
                    $display = [];
                    $display[] = '<a href="'.$preUrl.'admin/article/select/audit/' . $this->aid . '" target="_blank">' . $this->aid . '</a>';

                    return implode('<br/>', $display);
                })->width(200)->copyable();
                $grid->column('uid', '用户信息')->display(function() use ($kaUidList, $preUrl, $teamMap) {
                    return self::_getUserInfo($this->uid, $kaUidList, $preUrl, $teamMap);
                })->width(150);
                $grid->column('admin_comment', '额外信息')->display(function () {
                    if (empty($this->admin_comment)) {
                        $comment_btn = "<a href='javascript:;' class='btn btn-default addComment'  data-id='$this->aid' id='$this->aid'>运营评论</a>";
                    } else {
                        $comment_btn = "<a href='javascript:;' class='btn btn-success'  data-id='$this->aid' id='$this->aid'>$this->admin_comment 已评论</a>";
                    }
                    if (empty($this->admin_like)) {
                        $like_btn = "<a href='javascript:;' class='btn btn-default addLike'  data-id='$this->aid' id='like$this->aid'>运营点赞</a>";
                    } else {
                        $like_btn = "<a href='javascript:;' class='btn btn-success'  data-id='$this->aid' id='like$this->aid'>$this->admin_like 已点赞</a>";
                    }
                    $copy_btn = "<a href='javascript:;' class='btn btn-default copyH5'  data-id='$this->aid' >复制链接</a>";
                    if ($this->is_business) {
                        $businessBtn = "<a href='javascript:;' class='btn btn-success addBusiness'  data-id='$this->aid' id='business$this->aid'>商业</a>";
                    } else {
                        $businessBtn = "<a href='javascript:;' class='btn btn-default addBusiness'  data-id='$this->aid' id='business$this->aid'>商业</a>";
                    }
                    //					if (Admin::user()->isRole('partime.user')) {
                    //						return $comment_btn . "<br><br>" . $like_btn . "<br><br>" . $copy_btn;
                    //					}
                    return $comment_btn . "<br><br>" . $like_btn . "<br><br>" . $copy_btn . "<br><br>" . $businessBtn;
                })->width(150);
                $grid->column('admin_tag', '文章标签')->display(function () {
                    $options = '';
                    if ($this->admin_tag && is_array($this->admin_tag)) {
                        foreach ($this->admin_tag as $tag) {
                            $options = $options . '<button style="display:inline-block;margin:2px;" class="marktag btn btn-sm btn-primary" data-had="">' . $tag . '</button><br/>';
                        }
                    }
                    return $options;
                })->width(200);
                $grid->column("title", '文章信息')->display(function () {
                    $display = [];
                    $display[] = "<span style='font-size: 15px;width:10px; white-space:pre-wrap;'>标题:<b>" . $this->title . "</b></span>";
                    // $display[] ="<p style='font-size: 15px;width: 30px;  white-space:pre-wrap;'>标题:".$this->title."</p>" ;
                    if ($this->op_title) {
                        $display[] = "<sapn style='font-size: 15px'>精选标题:<b>" . $this->op_stitle . "</b></sapn>";
                    }
                    $display[] = "<sapn style='font-size: 15px'>使用面积:<b>" . $this->house_size . "</b>平米</sapn>";
                    $display[] = "<sapn style='font-size: 15px'>位置:<b>" . $this->area_name . "</b></sapn>";
                    $display[] = "<sapn style='font-size: 15px'>预算:<b>" . $this->house_stuff . "</b>万元</sapn>";
                    $display[] = "<sapn style='font-size: 15px'>居室:<b>" . FilterConfig::ROOM[$this->house_construction] . "</b></sapn>";

                    return implode('<br/>', $display);
                })->width(200);

                $grid->column("interact", '交互')->display(function () {
                    $display = [];
                    $display[] = "<sapn style='font-size: 15px'>点赞:<b>" . $this->like
                        . "</b></sapn>";
                    $display[] = "<sapn style='font-size: 15px'>收藏:<b>" . $this->favorite . "</b></sapn>";
                    $display[] = "<sapn style='font-size: 15px'>评论:<b>" . $this->comments . "</b></sapn>";

                    return implode('<br/>', $display);
                })->width(200);

                $grid->column('publish_time', '首发时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->publish_time);
                });
                $grid->column('user_update_time', '用户编辑时间')->display(function () {
                    if (empty($this->user_update_time)) {
                        return '-';
                    } else {
                        return date('Y-m-d H:i:s', $this->user_update_time);
                    }
                });

                $grid->column('same_infos', '疑似重复案例')->display(function () use ($preUrl) {
                    $str = "";
                    foreach ($this->same_infos as $aid => $sameInfo) {
                        $articleDetailUrl = $preUrl."admin/article/select/audit/" . $aid;
                        $str .= "案例id: <a href='{$articleDetailUrl}'  target='_blank' >{$aid}</a> 重复占比：{$sameInfo['same_rate']}";

                        if ($this->user_type == "设计师用户") {
                            $repeat_author = IdParse::getUid($aid);
                            $relation = MasterSlave::getRelation($this->uid, $repeat_author);
                            if (empty($relation)) {
                                $master_slave = '无';
                            } else {
                                $master_slave = MasterSlave::MASTER_SALVE[$relation];
                            }
                            $str .= "<p>uid：{$repeat_author}<br/>账号关系：{$master_slave}</p>";
                        }
                    }
                    return $str;
                });

                $grid->column('admin_score', '分数')->display(function () {
                    $display[] = '<p style="white-space:nowrap">' . FilterConfig::SCORE_CONTENT[$this->admin_score] . $this->admin_score . '</p>';

                    if (Admin::user()->can('article-Audit-D')) {
                        $url = '/admin/article/select/bestForm/' . $this->aid;

                        $display[] = '<a href="javascript:layer.open({
                        type: 2,
                            title: \'精选\',
                            maxmin: true,
                            area: [\'400px\', \'500px\'],
                            content: \'' . $url . '\'
                    });"    data-score="80" class="label  grade_2 label-info"> 精选  </a><br/>';
                    if ($this->admin_score > 70) {

                        $display[] = '<a class="	delbest label  label-default" data-id="' . $this->aid . '"  href="javascript:void(0);">取消精选</a>';

                    }
                    }
                    return implode('<br/>', $display);
                })->width(200);;

                $grid->column('audit_status', '审核')->display(function ($title, Grid\Column $column) {
                    if ($this->audit_status == '已审核') {
                        return $column->label('success');
                    } else if ($this->audit_status == '未审核') {
                        return $column->label('warning');
                    } else if ($this->audit_status == '待复审') {
                        return $column->label('danger');
                    }
                });
                $grid->column('admin_name', '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '暂无';
                    } else {
                        return $this->admin_name;
                    }
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $url = 'https://m.haohaozhu.cn/bangyang/' . $actions->row->aid . '.html?preview=1';
                    $actions->prepend('<p style="white-space:nowrap"><a class="fa fa-envelope" href="javascript:layer.open({
                    type: 2,
                        title: \'预览\',
                        maxmin: true,
                        area: [\'800px\', \'500px\'],
                        content: \'' . $url . '\'
                });">预览  </a></p>');

                $actions->prepend('<p style="white-space:nowrap"><a class="label  label-info" href="javascript:layer.open({
                type: 2,
                    title: \'小程序二维码\',
                    maxmin: true,
                    area: [\'450px\', \'500px\'],
                    content: \'/admin/article/select/qrCode/' . $actions->row->aid . '\'
                });">查看小程序二维码</a></p>');
                });
            });

        $tab = new Tab();
        $tab->add('整屋筛选', $gridList->render());

        $content->row($tab);

        return $content
            ->header('设计师整屋筛选')
            ->description(' ')
            ->breadcrumb(
                ['text' => '整屋列表', 'url' => '/article/select/index']
            );
    }

    public function FormateType($uid,$type){
        $all_type = Member::$typeDesc;
        foreach ($all_type as $key => $value){
            if ($type == Member::AUTH_USER_BRAND){
                $brand_type = sUser::getBrandInfo($uid)['type'];
                if ($brand_type == Brand::TYPE_BRAND){
                    $type = '认证品牌';
                }elseif ($brand_type == Brand::TYPE_SHOP){
                    $type = '认证店铺';
                }
            }elseif($type == $key) {
                $type = $value;
            }
        }

        return $type;
    }

    public function FormateUserTag($uid) {
        $adm_tag = AdmUserType::getById($uid);
        $adm_userInfo = [];
        if (is_array($adm_tag)){
            $user_tag = $adm_tag['auth_tag'];
            $user_quality = $adm_tag['quality'];
            if ($user_tag == AdmUserType::AUTH_TAG_SUSPECTED_BUSINESS){
                $adm_userInfo['user_tag'] = '疑似商业用户';
            }elseif ($user_tag == AdmUserType::AUTH_TAG_WAIT_BRAND){
                $adm_userInfo['user_tag'] = '待认证品牌';
            }else{
                $adm_userInfo['user_tag'] = '无';
            }
            if ($user_quality == AdmUserType::B1){
                $adm_userInfo['user_quality'] = "B1用户";
            }elseif ($user_quality == AdmUserType::B2){
                $adm_userInfo['user_quality'] = "B2用户";
            }elseif ($user_quality == AdmUserType::B3){
                $adm_userInfo['user_quality'] = "B3用户";
            }elseif ($user_quality == AdmUserType::XL){
                $adm_userInfo['user_quality'] = "XL用户";
            }else{
                $adm_userInfo['user_quality'] = "无";
            }
        }else {
            $adm_userInfo['user_quality'] = "无";
            $adm_userInfo['user_tag'] = '无';
        }
        return $adm_userInfo;
    }
    /**
     * 获取用户信息拼接的字符串
     * @param $uid  用户uid
     * @param $kaUidList  ka用户列表
     * @param $preUrl  用户域名前缀
     * @param $teamMap 用户团队关系映射
     * @return string 获取用户信息拼接的字符串
     */
    private static function  _getUserInfo($uid, $kaUidList, $preUrl, $teamMap) {
        $userinfo = sUser::getBasicUserInfoByCache($uid);
        if(empty($userinfo)) { //用户信息不存在
            return  $uid;
        }
        $type = $userinfo['type'];
        $info = [
            'uid' => "<a href='".$preUrl."admin/user/Detail/{$uid}' target='_blank'>{$uid}</a>",
            '昵称' => $userinfo['nick'],
            '身份' => Member::$typeDesc[$type]
        ];


        switch($type) {
            case Member::AUTH_USER_BRAND:
                $brandinfo = sUser::getBrandInfo($uid);
                $sub_type = $brandinfo['brand_type'];
                $info['子身份'] = Brand::BRAND_TYPE[$sub_type];
                break;
            case Member::AUTH_USER_DESIGNER:
                $authinfo = AuthService::getAuthInfo($uid);
                $sub_type = $authinfo['designer_type'];
                $info['子身份'] = DesignerAuth::DESIGNER_TYPE[$sub_type];
                break;
        }


        $content = "";
        foreach($info as $key => $value) {
            $content .= "<div>{$key}：{$value}</div>";
        }

        // 对接运营
        $operator_show_name = '无';
        $operator_bind = DesignerOperatorBind::getInfoByUid($uid);
        if ($operator_bind && $operator_bind['operator_id']) {
            $operator_show_name = Operator::get('operator_show_name', [
                'id' => $operator_bind['operator_id']
            ]);
        }
        $content .= "<div>对接运营：<span style='font-weight: bold'>{$operator_show_name}</span></div>";

        //判读用户是否是KA
        if(in_array($uid, $kaUidList)) {
            $content .= "<div style='font-weight: bold'>hierarchy：KA</div>";
        } else if (isset($teamMap[$uid])) { //属于团队
            $teamUid = $teamMap[$uid];
            if(in_array($teamUid, $kaUidList)) { //判断团队是否是KA
                $content .= "<div style='font-weight: bold'>hierarchy：KA子账号</div>";
            }

        }

        return $content;
    }
}
